package com.scu.phototabuser.ui.taskgroup;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;

import com.facebook.drawee.view.SimpleDraweeView;
import com.scu.phototabuser.Consts;
import com.scu.phototabuser.R;
import com.scu.phototabuser.ui.home.HomeActivity;
import com.scu.phototabuser.ui.navitems.MineDetailActivity;
import com.scu.phototabuser.util.Predictions;
import com.scu.phototabuser.util.PreferenceUtil;
import com.scu.phototabuser.util.ToastUtil;
import com.scu.phototabuser.util.WindowUtil;
import com.yanzhenjie.recyclerview.swipe.SwipeMenu;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuAdapter;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuCreator;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuItem;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuRecyclerView;

import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by tianfei on 2017/4/30.
 */

public class ChooseGroupActivity extends AppCompatActivity{

    @BindView(R.id.recycler)
    SwipeMenuRecyclerView recyclerView;

    @BindView(R.id.floating_btn_message)
    FloatingActionButton btn_show_message;

    @BindView(R.id.tool_bar)
    Toolbar toolbar;

    //菜单创建器。在SwipeMenuRecyclerView的Item要创建菜单的时候调用。
    private SwipeMenuCreator swipeMenuCreator = new SwipeMenuCreator(){
        @Override
        public void onCreateMenu(SwipeMenu swipeLeftMenu, SwipeMenu swipeRightMenu, int viewType) {

            SwipeMenuItem typeName = new SwipeMenuItem(ChooseGroupActivity.this)
                    //.setBackgroundDrawable(R.drawable.selector_red)
                    //.setImage(R.mipmap.) // 图标。
                    .setText(ImageType.getMsgFromType(viewType)) // 文字。
                    .setTextColor(ContextCompat.getColor(ChooseGroupActivity.this,R.color.colorAccent)) // 文字颜色。
                    .setTextSize(16) // 文字大小。
                    .setWidth(getResources().getDimensionPixelSize(R.dimen.sliding_menu_width))
                    .setHeight(ViewGroup.LayoutParams.MATCH_PARENT);
            swipeRightMenu.addMenuItem(typeName);// 添加一个按钮到右侧侧菜单。.

        }
    };

    private MyMenuViewTypeAdapter adapter;

    //记录用户选中的类型
    //使用Map是因为Map删除和查找比ArrayList快
    private HashSet<Integer> selectedTypes = new HashSet<>();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_show_choose_type);
        ButterKnife.bind(this);

        toolbar.setTitle(Consts.CHOOS_TYPES);
        toolbar.setTitleTextColor(ContextCompat.getColor(ChooseGroupActivity.this,R.color.colorAccent));
//        toolbar.setNavigationIcon(R.drawable.ic_keyboard_backspace_black_24dp);
//        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                //如果是第一次初始化App，点击后会直接关闭
//                //如果在设置界面进入，点击后会回退到设置界面
//                onBackPressed();
//            }
//        });
        setSupportActionBar(toolbar);

        btn_show_message.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Snackbar.make(v, Consts.CHOOSE_GROUP_ACTIVITY_SHOW_HELP_MESSAGE, Snackbar.LENGTH_LONG)
                        .show();
            }
        });

        // 设置菜单创建器。
        recyclerView.setSwipeMenuCreator(swipeMenuCreator);
        //设置瀑布流布局
        recyclerView.setLayoutManager(new StaggeredGridLayoutManager(Consts.IMAGE_COLUMNS,StaggeredGridLayoutManager.VERTICAL));
        //recyclerView.addItemDecoration(new ListViewD());
        initData();

        //第一次打开界面显示帮助语句
        btn_show_message.callOnClick();
    }

    private void initData(){

        String baseUri="res://"+this.getPackageName()+"/";

        // FIXME: 2017/5/2 修改写死的逻辑代码
        Map<Integer,String> map=new HashMap<>();
        final ImageType[] types=ImageType.class.getEnumConstants();
        int[] imgWidths = new int[types.length];
        int[] imgHeights= new int[types.length];


        int flag=0;
        for (ImageType i:types){
            //存放Integer到图片地址的转换
            int resID = getResources().getIdentifier(i.toString().toLowerCase() , "drawable", getPackageName());

            //初始化图片高度和宽度数组
            Drawable d=getDrawable(resID);
            imgWidths[flag]=d.getIntrinsicWidth();
            imgHeights[flag]=d.getIntrinsicHeight();
            flag++;

            //初始化数据Map
            map.put(i.getType(),baseUri+resID);
        }

        adapter=new MyMenuViewTypeAdapter(ChooseGroupActivity.this,
                imgWidths,imgHeights,map);
        adapter.setRecyclerViewClickListener(new MyMenuViewTypeAdapter.RecyclerViewClickListener() {
            @Override
            public void onItemClick(View v, int type) {

                if (v.getAlpha() != 0.65f){

                    ImageView imgCheck=new ImageView(ChooseGroupActivity.this);
                    imgCheck.setImageResource(R.drawable.ic_red_white_check_24dp);
                    //设置margin
                    FrameLayout.LayoutParams marginParams=new FrameLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
                            ViewGroup.LayoutParams.WRAP_CONTENT);
                    marginParams.width=60;
                    marginParams.height=60;
                    marginParams.setMargins(10,10,0,0);
                    imgCheck.setLayoutParams(marginParams);
                    //添加tag 便于删除时查找
                    imgCheck.setTag("check");

                    //在selectedTypes中记录
                    selectedTypes.add(type);
                    v.setAlpha(0.65f);
                    ((ViewGroup)v).addView(imgCheck);
                }else {
                    //从selectedTypes中移除
                    selectedTypes.remove(type);
                    v.setAlpha(1f);
                    ((ViewGroup)v).removeView(v.findViewWithTag("check"));
                }

            }

            @Override
            public void onItemLongClick(View v, int type) {
                //// FIXME: 2017/5/2 修改业务逻辑
                ToastUtil.makeAppContextToast("You long clicked image, type is: "+type);
            }
        });

        recyclerView.setAdapter(adapter);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.ok_btn,menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        if (item.getItemId() == R.id.menu_btn_ok){


            if (selectedTypes.size() == 0){
                //用户什么都没有选，弹出对话框提示用户是否继续
                final AlertDialog.Builder builder=new AlertDialog.Builder(ChooseGroupActivity.this);
                builder.setIcon(R.drawable.ic_red_warning_24dp);
                builder.setTitle(Consts.CONTINUE);
                builder.setView(R.layout.dialog_tv);
                builder.setPositiveButton(getString(R.string.i_am_sure), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        Integer[] arr=MyMenuViewTypeAdapter.getAllTypes();
                        saveTypeAndFinishThis(arr);
                    }
                });
                builder.setNegativeButton(getString(R.string.i_will_rethink), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {}
                });
                builder.show();
            }

            else {
                //保存用户选中的Types到本地
                Integer[] arr = new Integer[selectedTypes.size()];
                saveTypeAndFinishThis(arr);
            }
        }
        return true;
    }

    private void saveTypeAndFinishThis(Integer[] arr){
        //保存用户选中的Types到本地
//        Integer[] arr = new Integer[selectedTypes.size()];
        selectedTypes.toArray(arr);

        PreferenceUtil.saveUserChosenTypes(Predictions.parseStringFromUserTypeArray(arr));

        //fixme 触发上传用户选中的Types到服务器的任务 ----->NewThread
        //upload

        //如果是从用户详情界面跳转而来，finish掉当前即可
        if (getIntent().getExtras().getBoolean(Consts.ACTION_MINEDETAIL_CHANGE_USER_CHOSEN_TYPE)){
            finish();
            return;
        }
        //直接结束掉当前Activity，由UserChosenDecisionMaker决定跳转到HOME
        Intent i=new Intent(this,UserChosenDecisionMaker.class);
        startActivity(i);
        finish();
    }

    // FIXME: 2017/5/2 后续添加请求服务器更新Type种类的方法
    static class MyMenuViewTypeAdapter extends SwipeMenuAdapter<MyMenuViewTypeAdapter.DefaultViewHolder>
            implements View.OnClickListener ,View.OnLongClickListener{

        interface RecyclerViewClickListener {
            void onItemClick(View v,int type);
            void onItemLongClick(View v,int type);
        }

        private RecyclerViewClickListener recyclerViewClickListener =null;

        //K必须是ViewType中的一种Type
        //V是该种Type对应的说明图片的uri
        private Map<Integer,String> contentMap;
        //keySet 是contentMap中使用的Key的线性排列数组,也就是说KeySet中的值也必须是ViewType中的一种Type
        private static Integer[] arrayKeySet = new Integer[ImageType.values().length];
        static {
            int flag=0;
            for (ImageType i:ImageType.values()){
                //存放Integer到数组
                arrayKeySet[flag++]=i.getType();
            }
        }

        private int[] imgWidths;
        private int[] imgHeights;
        private Context context;

        MyMenuViewTypeAdapter(Context context,int[] imgWidths,int[] imgHeights,Map<Integer,String> map) {
            this.context=context;
            this.contentMap=map;
            this.imgWidths = imgWidths;
            this.imgHeights = imgHeights;
        }


        void setRecyclerViewClickListener(RecyclerViewClickListener recyclerViewClickListener) {
            this.recyclerViewClickListener = recyclerViewClickListener;
        }

        @Override
        public int getItemViewType(int position) {
            return arrayKeySet[position];
        }

        @Override
        public int getItemCount() {
            return arrayKeySet.length == 0 ? 0 : arrayKeySet.length;
        }

        @Override
        public View onCreateContentView(ViewGroup parent, int viewType) {

            View v= LayoutInflater.from(context).inflate(R.layout.item_imgview,parent,false);

            //view set tag，方便在点击时直接拿出图片对应的Type
            v.setTag(viewType);
            v.setOnClickListener(this);
            v.setOnLongClickListener(this);
            return v;
        }

        static Integer[] getAllTypes(){
            return Arrays.copyOf(arrayKeySet,arrayKeySet.length);
        }



        @Override
        public MyMenuViewTypeAdapter.DefaultViewHolder onCompatCreateViewHolder(View realContentView, int viewType) {
            return new DefaultViewHolder(realContentView);
        }

        @Override
        public void onBindViewHolder(MyMenuViewTypeAdapter.DefaultViewHolder holder, int position) {

            //设置ImageView的大小
            int width=imgWidths[position];
            int height=imgHeights[position];
            holder.setImageLayout(width,height);

            //给ImageView设置图片Uri
            holder.img.setImageURI(contentMap.get(arrayKeySet[position]));
        }


        @Override
        public void onClick(View v) {
            if (recyclerViewClickListener != null && v.getTag()!=null){
                recyclerViewClickListener.onItemClick(v, (Integer)v.getTag());
            }
        }

        @Override
        public boolean onLongClick(View v) {

            if (recyclerViewClickListener != null && v.getTag()!= null){
                recyclerViewClickListener.onItemLongClick(v, (Integer)v.getTag());
            }

            //返回TRUE表示拦截这次点击事件，否则抬起手后会继续触发onClick事件
            return true;
        }


        class DefaultViewHolder extends RecyclerView.ViewHolder{

            private SimpleDraweeView img;
            private FrameLayout imgRoot;

            DefaultViewHolder(View itemView) {
                super(itemView);
                img=(SimpleDraweeView)itemView.findViewById(R.id.item_img);
                imgRoot=(FrameLayout)itemView.findViewById(R.id.item_img_root);
            }

            void setImageLayout(int width, int height){

                height= WindowUtil.pxToDp(height);
                width = WindowUtil.pxToDp(width);

                ViewGroup.LayoutParams params=img.getLayoutParams();
                //获取Grid每一列
                //设置每张图片宽度为GridLayout列宽
                params.width=WindowUtil.getWindowWidthPx()/Consts.IMAGE_COLUMNS;
                params.height=(height*params.width)/width;
                img.setLayoutParams(params);
            }
        }
    }
}
